<template>
  <div class="login-container">
    <el-dialog
      title="添加分类"
      :visible.sync="dialogVisibleAdd"
      width="900px"
      :show-close="false">
      <span>
        <span>
          <el-form :model="addCategory" :rules="categoryRules" ref="addCategory" label-width="110px">
            <el-row>
              <el-col :span="9">
                <el-form-item label="分类名称：" prop="catName">
                  <el-input v-model="addCategory.catName" placeholder="请输入分类名称"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="分类排序：" prop="sortOrder">
                  <el-input v-model="addCategory.sortOrder" placeholder="请输入分类排序"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </span>
        <span v-show="attributeAddShow">
          <el-row>
            <el-col :span="18">
              <el-form :model="addAttributeForm" :rules="attributeFormRules" ref="addAttributeForm" label-width="110px">
                <el-row>
                  <el-col :span="12">
                    <el-form-item
                      v-for="(addAttribute, index) in addAttributeForm.addAttributes"
                      :label="'分类属性-' + (index+1) + '：'"
                      :key="addAttribute.keyId"
                      :prop="'addAttributes.' + index + '.attrName'"
                      :rules="attributeFormRules.attrName">
                      <el-input v-model="addAttribute.attrName" placeholder="请输入属性名称"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item
                      v-for="(addAttribute, index) in addAttributeForm.addAttributes"
                      :label="'属性排序-' + (index+1) + '：'"
                      :key="addAttribute.keyId"
                      :prop="'addAttributes.' + index + '.sortOrder'"
                      :rules="attributeFormRules.sortOrder">
                      <el-row>
                        <el-col :span="12">
                          <el-input v-model="addAttribute.sortOrder" placeholder="请输入属性排序"></el-input>
                        </el-col>
                        <el-col :span="10" :offset="2">
                          <el-button @click.prevent="removeAddAttribute(addAttribute)" icon="el-icon-delete"></el-button>
                        </el-col>
                      </el-row>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </el-col>
            <el-col :span="6">
              <el-button @click="addAddAttribute"  icon="el-icon-plus"></el-button>
              <el-button @click="resetAddAttribute('addAttributeForm')"  >重置</el-button>
            </el-col>
          </el-row>
        </span>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleAddButton('addCategory',0)">取 消</el-button>
        <el-button type="primary" @click="dialogVisibleAddButton('addCategory',1)">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="分类编辑"
      :visible.sync="dialogVisibleEdit"
      width="900px"
      :show-close="false">
      <span>
        <span>
          <el-form :model="editCategory" :rules="categoryRules" ref="editCategory" label-width="100px">
            <el-row>
              <el-col :span="9">
                <el-form-item label="分类名称：" prop="catName">
                  <el-input v-model="editCategory.catName" placeholder="分类名称"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="分类排序：" prop="sortOrder">
                  <el-input v-model="editCategory.sortOrder" placeholder="请输入分类排序"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </span>
        <span v-show="attributeEditShow">
          <el-row>
            <el-col :span="18">
              <el-form :model="editAttributeForm" :rules="attributeFormRules" ref="editAttributeForm" label-width="110px">
                <el-row>
                  <el-col :span="12">
                    <el-form-item
                      v-for="(editAttribute, index) in editAttributeForm.editAttributes"
                      :label="'分类属性-' + (index+1) + '：'"
                      :key="editAttribute.keyId"
                      :prop="'editAttributes.' + index + '.attrName'"
                      :rules="attributeFormRules.attrName">
                      <el-input v-model="editAttribute.attrName" placeholder="请输入属性名称"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item
                      v-for="(editAttribute, index) in editAttributeForm.editAttributes"
                      :label="'属性排序-' + (index+1) + '：'"
                      :key="editAttribute.keyId"
                      :prop="'editAttributes.' + index + '.sortOrder'"
                      :rules="attributeFormRules.sortOrder">
                      <el-row>
                        <el-col :span="12">
                          <el-input v-model="editAttribute.sortOrder" placeholder="请输入属性排序"></el-input>
                        </el-col>
                        <el-col :span="10" :offset="2">
                          <el-button @click.prevent="removeEditAttribute(editAttribute)" icon="el-icon-delete"></el-button>
                        </el-col>
                      </el-row>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </el-col>
            <el-col :span="6">
              <el-button @click="addEditAttribute"  icon="el-icon-plus"></el-button>
              <!--<el-button @click="resetEditAttribute('editAttributeForm')"  >重置</el-button>-->
            </el-col>
          </el-row>
        </span>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleEditButton('editCategory',0)">关 闭</el-button>
        <el-button type="primary" @click="dialogVisibleEditButton('editCategory',1)">确 定</el-button>
      </span>
    </el-dialog>

    <el-button @click="handleAddTop">添加顶级节点</el-button>
    <div class="block" style="margin-top: 20px">
      <el-tree
        :data="categoryTreeData"
        node-key="dialogId"
        :props="defaultProps"
        :expand-on-click-node="false"
        :default-expand-all="true">
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
          <span style="padding-left: 100px">
            <el-button
              type="text"
              size="mini"
              @click="() => append(node,data)">
              <i class="el-icon-plus"></i>
            </el-button>
            <el-button
              type="text"
              size="mini"
              @click="() => treeEdit(node,data)">
              <i class="el-icon-tickets"></i>
            </el-button>
            <el-button
              type="text"
              size="mini"
              @click="() => remove(node,data)">
              <i class="el-icon-minus"></i>
            </el-button>
          </span>
        </span>
      </el-tree>
    </div>
  </div>
</template>

<script>
  import 'element-ui/lib/theme-chalk/display.css'
  import pagesApi from '@/api/backstage/pages'
  import Code from '@/utils/code'

  let dialogId = 1000;
  export default {
    inject:['reload'],
    name: 'Category',
    data() {
      const validateId = (rule, value, callback) => {
        callback();
      }
      const validateParentId = (rule, value, callback) => {
        callback();
      }
      const validateDialogId = (rule, value, callback) => {
        callback();
      }
      const validateCatName = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入分类名称！'));
        }
        if (value.length > 10){
          callback(new Error('分类名称不能超过10个字'));
        }
        callback();
      }
      const validateSortOrder = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入分类名称！'));
        }
        let sortOrderRule = /^(?!0)(?:[0-9]{1,3}|1000)$/
        if (!sortOrderRule.test(value)){
          callback(new Error('属性值范围1~1000'));
        }
        callback();
      }
      const validateAttributeAttrName = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入属性名称！'));
        }
        if (value.length > 10){
          callback(new Error('属性名称不能超过10个字'));
        }
        callback();
      }
      const validateAttributeSortOrder = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入属性排序值！'));
        }
        let sortOrderRule = /^(?!0)(?:[0-9]{1,3}|1000)$/
        if (!sortOrderRule.test(value)){
          callback(new Error('属性值范围1~1000'));
        }
        callback();
      }
      return{
        categoryTreeData: [],
        defaultProps: {
          children: 'children',
          label: 'catName'
        },
        /*触发的tree当前的节点，放到全局，方便调用*/
        triggerCurrenNodeData: {},
        triggerCurrenNodeDataValue: {},
        /*触发的tree当前节点*/
        triggerCurrenNode:{},
        triggerCurrenNodeValue:{},
        addCategory:{
          id: '',
          parentId: '',
          dialogId: '',
          catName: '',
          sortOrder:''
        },
        addAttributeForm:{
          addAttributes: [
            {attrId:'',catId:'',keyId:10, attrName:'',sortOrder:''}
            ],
        },
        editAttributeForm:{
          editAttributes: [
            {attrId:'',catId:'',keyId:10, attrName:'',sortOrder:''}
          ],
        },
        editCategory: {
          id: '',
          parentId: '',
          dialogId: '',
          catName: '',
          sortOrder:''
        },
        categoryRules: {
          id: [{required: true, trigger: 'blur', validator: validateId}],
          parentId: [{required: true, trigger: 'blur', validator: validateParentId}],
          dialogId: [{required: true, trigger: 'blur', validator: validateDialogId}],
          catName: [{required: true, trigger: 'blur', validator: validateCatName}],
          sortOrder: [{required: true, trigger: 'blur', validator: validateSortOrder}]
        },
        attributeFormRules:{
          attrName:[{required: true, trigger: 'blur', validator: validateAttributeAttrName}],
          sortOrder:[{required: true, trigger: 'blur', validator: validateAttributeSortOrder}]
        },
        attributeAddShow: true,
        attributeEditShow: true,
        dialogVisibleAdd: false,
        addTopTree: true,
        dialogVisibleEdit: false,
      };
    },
    created() {
      this.initData()
    },
    methods: {
      initData(){
        pagesApi.getCategory({showInNav:1,display:1}).then(res => {
          this.categoryTreeData = res.data;
        })
      },
      /** 添加节点 start **/
      append(node, data) {
        //添加子节点
        if (node.level > 2) {
          this.$notify.warning({title:'提示', message:'最多只支持三级！'});
          return false;
        }
        this.dialogVisibleAdd = true;
        this.triggerCurrenNodeData = data;
        this.triggerCurrenNode = node;
        this.addTopTree = false; //不是添加顶级节点
        this.attributeAddShow = true;//添加子节点，显示添加属性
        this.addAttributeForm.addAttributes = [{attrId:'',catId:'',keyId:10, attrName:'',sortOrder:''}];
        // this.addAttributeForm.addAttributes = [];
        this.$nextTick(()=>{
          this.$refs.addCategory.resetFields();
          this.$refs.addAttributeForm.resetFields();
        });
      },
      handleAddTop(){
        // 添加顶级节点
        this.dialogVisibleAdd = true;
        this.addTopTree = true; //添加顶级节点
        this.attributeAddShow = false;//添加top节点，不显示添加属性
        // this.addAttributeForm.addAttributes = [{attrId:'',catId:'',keyId:10, attrName:'',sortOrder:''}];
        this.addAttributeForm.addAttributes = [];
        this.$nextTick(()=>{
          this.$refs.addCategory.resetFields();
          this.$refs.addAttributeForm.resetFields();
        });
      },
      /** 添加弹出框start **/
      dialogVisibleAddButton(addCategory, value){
        // 确定按钮 添加节点
        // 1 为确定按钮， 0为取消按钮
        if (value === 1) {
          this.$refs[addCategory].validate(valid => {
            if (valid) {
              if (this.addTopTree){
                //添加顶级节点
                let categoryInfo = {
                  catName: this.addCategory.catName,
                  sortOrder: this.addCategory.sortOrder
                }
                pagesApi.saveCategory(categoryInfo, null).then(res => {
                  if (res.code == Code.SERVICE_FAIL) {
                    this.$notify.error({title:'警告', message:'添加失败！'});
                    this.dialogVisibleAdd = true;
                    return false;
                  }
                  // const newChild = {
                  //   id: res.data.id,
                  //   dialogId: res.data.dialogId,
                  //   catName: res.data.catName,
                  //   children: []
                  // };
                  // this.categoryTreeData.push(newChild);
                  this.reload();
                  // this.dialogVisibleAdd = false;
                }).catch(() => {
                  this.$notify.error({title:'警告', message:'添加失败！'});
                  this.dialogVisibleAdd = true;
                  return false;
                })
              } else {
                // 添加子节点
                let categoryInfo = {
                  parentId: this.triggerCurrenNodeData.id,
                  catName: this.addCategory.catName,
                  sortOrder: this.addCategory.sortOrder
                }
                this.$refs.addAttributeForm.validate(valid => {
                  if (valid) {
                    // 属性值
                    let attributeInfo = JSON.parse(JSON.stringify(this.addAttributeForm.addAttributes));
                    pagesApi.saveCategory(categoryInfo,attributeInfo).then(res => {
                      if (res.code == Code.SERVICE_FAIL) {
                        this.$notify.error({title:'警告', message:'添加失败！'});
                        this.dialogVisibleAdd = true;
                        return false;
                      }
                      // const newChild = {
                      //   id: res.data.id,
                      //   parentId: res.data.parentId,
                      //   dialogId: res.data.dialogId,
                      //   catName: res.data.catName,
                      //   children: []
                      // };
                      // if (!this.triggerCurrenNodeData.children) {
                      //   this.$set(this.triggerCurrenNodeData, 'children', []);
                      // };
                      // this.triggerCurrenNodeData.children.push(newChild);

                      this.reload();
                      // this.initData();
                      // this.dialogVisibleAdd = false;
                    }).catch(() => {
                      this.$notify.error({title:'警告', message:'添加失败！'});
                      this.dialogVisibleAdd = true;
                      return false;
                    })
                  } else {
                    this.$notify.warning({title:'提示', message:'输入合规的数据！'});
                    this.dialogVisibleAdd = true;
                    return false;
                  }
                });
              }
            } else {
              this.$notify.warning({title:'提示', message:'输入合规的数据！'});
              this.dialogVisibleAdd = true;
              return false;
            }
          })
        } else {
          this.dialogVisibleAdd = false;
        }
      },
      /** 添加弹出框 end **/
      /** 添加节点 end **/
      /** 编辑节点 strat **/
      treeEdit(node, data){
        this.dialogVisibleEdit = true;
        this.triggerCurrenNodeData = data;
        this.triggerCurrenNode = node;
        this.$nextTick(()=>{
          this.$refs.editCategory.resetFields();
          this.editCategory = this.copyObject(data);
          this.$refs.editAttributeForm.resetFields();
        });
        if (data.hasOwnProperty('parentId') && data.parentId.length == 32) {
          /** 子节点 **/
          /** 该节点是子节点，显示属性列 **/
          this.attributeEditShow = true;
          this.editAttributeForm.editAttributes = [{attrId:'',catId:'',keyId:10, attrName:'',sortOrder:''}];
          pagesApi.getAttributeInfos({catId:data.id}).then(res => {
            /** 获取节点属性 **/
            this.editAttributeForm.editAttributes = JSON.parse(JSON.stringify(res.data));
          }).catch(() => {
            this.$notify.warning({title:'提示', message:'节点属性获取失败！'});
            this.attributeEditShow = true;
            return false;
          })
        } else {
          /** top节点 **/
          /** 该节点是top节点，不显示添加属性 **/
          this.attributeEditShow = false;
        }
      },
      dialogVisibleEditButton(catrgory, value){
        /** 编辑分类 **/
        if (value === 1){
          /** 确定按钮 **/
          this.$refs[catrgory].validate(valid => {
              if (valid) {
                if (this.editCategory.hasOwnProperty('parentId') && this.editCategory.parentId.length == 32) {
                  /** 存在父节点，该节点不是Top节点 **/
                  this.$refs.editAttributeForm.validate(valid => {
                    /** 节点属性校验**/
                    if (valid) {
                      /** 节点属性校验合规 **/
                      let categoryInfo = {
                        id: this.editCategory.id,
                        dialogId: this.editCategory.dialogId,
                        catName: this.editCategory.catName,
                        sortOrder: this.editCategory.sortOrder
                      }
                      let attributeInfo = JSON.parse(JSON.stringify(this.editAttributeForm.editAttributes));
                      pagesApi.updateCategory(categoryInfo, attributeInfo).then(res => {
                        // /** 保存节点数据 **/
                        // this.triggerCurrenNodeData.catName = res.data.catName;
                        // this.triggerCurrenNodeData.sortOrder = res.data.sortOrder;
                        // /** 节点编辑成功，退出 **/
                        // this.dialogVisibleEdit = false;
                        // this.initData();
                        if (res.code == Code.SUCC){
                          this.reload();
                          return true;
                        }
                        this.$notify.warning({title:'提示', message:res.message});
                        return false;
                      }).catch(() => {
                        /** 节点编辑失败 **/
                        this.$notify.error({title:'警告', message:'编辑失败！'});
                        this.dialogVisibleEdit = true;
                        return false;
                      })
                    } else {
                      /** 节点属性校验不合规 **/
                      this.$notify.info({title:'提示', message:'输入合规的数据！'});
                      this.dialogVisibleEdit = true;
                      return false;
                    }
                  });
                } else {
                  /** 该节点是Top节点 **/
                  let categoryInfo = {
                    id: this.editCategory.id,
                    dialogId: this.editCategory.dialogId,
                    catName: this.editCategory.catName,
                    sortOrder: this.editCategory.sortOrder
                  }
                  pagesApi.updateCategory(categoryInfo, null).then(res => {
                    // /** 保存顶级节点数据 **/
                    // this.triggerCurrenNodeData.catName = res.data.catName;
                    // this.triggerCurrenNodeData.sortOrder = res.data.sortOrder;
                    // /** 顶级节点编辑成功，退出 **/
                    // this.dialogVisibleEdit = false;
                    // this.initData();
                    if (res.code == Code.SUCC){
                      this.reload();
                      return true;
                    }
                    this.$notify.warning({title:'提示', message:'res.message'});
                    return false;
                  }).catch(() => {
                    this.$notify.error({title:'提示', message:'编辑失败！'});
                    this.dialogVisibleEdit = true;
                    return false;
                  })
                }

              }else {
                /** 分类数据不合规 **/
                this.$notify.info({title:'提示', message:'输入合规的数据！'});
                this.dialogVisibleEdit = true;
                return false;
              }
          });
        } else {
          /** 取消按钮 **/
          this.dialogVisibleEdit = false;
        }
      },
      /** 编辑节点 end **/
      /** 删除节点 start **/
      remove(node, data){
        let categoryInfo = {
          id: ''
        };
        if (!data.id){
          this.$notify.error({title:'警告', message:'删除失败，请稍后试'});
          return false;
        }
        categoryInfo.id = data.id;
        pagesApi.deleteCategory(categoryInfo).then(res => {
          if (res.code == Code.SUCC){
            // this.initData();
            this.reload();
            return true;
          }
          this.$notify.warning({title:'提示', message:res.message});
          return false;
        }).catch(() => {
          this.$notify.error({title:'警告', message:'删除失败！'});
          return false;
        })
      },
      /** 删除节点 start **/
      /** 添加节点，添加属性 start **/
      removeAddAttribute(item){
        let index = this.addAttributeForm.addAttributes.indexOf(item);
        if (index !== -1){
          this.addAttributeForm.addAttributes.splice(index, 1);
        }
      },
      addAddAttribute(){
        if (this.addAttributeForm.addAttributes.length == 0) {
          this.addAttributeForm.addAttributes = [{attrId:'',catId:'',keyId:10, attrName:'',sortOrder:''}];
        } else {
          let maxKeyId = this.addAttributeForm.addAttributes[this.addAttributeForm.addAttributes.length - 1].keyId;
          this.addAttributeForm.addAttributes.push({attrId:'',catId:'',keyId:maxKeyId+1, attrName:'',sortOrder:''});
        }
      },
      resetAddAttribute(formName){
        this.$refs[formName].resetFields();
      },// 添加节点，添加属性 end
      // 编辑属性 start
      removeEditAttribute(item){
        let index = this.editAttributeForm.editAttributes.indexOf(item);
        if (index !== -1){
          this.editAttributeForm.editAttributes.splice(index, 1);
        }
      },
      addEditAttribute(){
        if (this.editAttributeForm.editAttributes.length == 0) {
          this.editAttributeForm.editAttributes = [{attrId:'',catId:'',keyId:10, attrName:'',sortOrder:''}];
        } else {
          let maxKeyId = this.editAttributeForm.editAttributes[this.editAttributeForm.editAttributes.length - 1].keyId;
          this.editAttributeForm.editAttributes.push({attrId:'',catId:'',keyId:maxKeyId+1, attrName:'',sortOrder:''});
        }
      },
      resetEditAttribute(formName){
        this.$refs[formName].resetFields();
      },
      /** 编辑属性 end **/
      /** 工具方法 **/
      copyObject(obj){
        return JSON.parse(JSON.stringify(obj));
      }
    }
  }
</script>
